<?php
namespace MyClass;
define("TOKEN", "jiangsuwanrun");
header("Content-Type: text/html; charset=UTF-8");
class choujiang extends \C\Action{

	public function valid(){
		$echoStr = $_GET["echostr"];
		//valid signature , option
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
	
	}
	private function checkSignature()
	{
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];

		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}

		



//	获取用户基本信息


	public function hqaccess_token(){
		$APPID="wx8921eeb67b2af283";
		$APPSECRET = "36b59af4dd03f6c6601379a3e2d84a65";
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$APPSECRET;
		$data = $this->https_request($url);
		
		return $data['access_token']; 
	
	}


	public function getBaseInfo() {//获取用户openid
		//用户同意授权，获取code
		$appid= 'wx8921eeb67b2af283';
		$redirect_url=urlencode('https://wap.chnhuacai.com/?m=choujiang&a=userhq');
		$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_url.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
		header('location:'.$url);
	}
	
	

	public function userhq(){//获取用户openid
	
	
		//通过code换取网页授权access_token
		$appid = 'wx8921eeb67b2af283';
		$secret =  '36b59af4dd03f6c6601379a3e2d84a65';
		$code=$_GET['code'];
		$url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code ';
	
		
		$data = $this->https_request($url);

		$ACCESS_TOKEN = $this->hqaccess_token();
		
		$OPENID = $data['openid'];
		
		$urluser='https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$ACCESS_TOKEN.'&openid='.$OPENID.'&lang=zh_CN';
		$datauser = $this->https_request($urluser);
		if($datauser['subscribe']==0){
			$this->error("请先关注公众号");
		
		}else{
			
			   $postUrl = "https://wap.chnhuacai.com/?m=choujiang&a=yyy";
				$param=array(
					"wxname"=>$datauser['nickname'],
					"OpenId"=>$datauser['openid']
				
				);
				$curlPost = $param;
				$headers = array('Content-Type: application/x-www-form-urlencoded');
				$curl = curl_init(); // 启动一个CURL会话
				curl_setopt($curl, CURLOPT_URL, $postUrl); // 要访问的地址
				curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
				curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
				curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
				curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
				curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
				curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
				curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($curlPost)); // Post提交的数据包
				curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
				curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
				curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
				$result = curl_exec($curl); // 执行操作
				if (curl_errno($curl)) {
					echo 'Errno'.curl_error($curl);//捕抓异常
				}
				curl_close($curl); // 关闭CURL会话
				
				
				echo  $result;	
				//header('location:http://wap.chnhuacai.com/?m=choujiang&a=yyy');
		}
		
	}


	public function https_request($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $out = curl_exec($ch);
        curl_close($ch);
        return  json_decode($out,true);
	}
	public function yyy2(){
	
		$this->v();
	}
	public function yyy4(){
	
		$this->v();
	}
    //转盘抽奖
    public function index(){
		$this->v();
	}
	public function getNums(){
		//中奖算法 所有总的奖品数
	}
	//滚动抽奖
	public function pcweb(){
		$list=array(
			array("id"=>1,"level"=>"特等奖","name"=>"一万元奖金","num"=>"1"),
			array("id"=>2,"level"=>"一等奖","name"=>"华为mate20","num"=>"2"),
			array("id"=>3,"level"=>"二等奖","name"=>"平板电脑","num"=>"5"),
			array("id"=>4,"level"=>"三等奖","name"=>"伍佰元","num"=>"10"),
		);
		$this->s("list",$list);
		$this->v();
	}
	public function GetPhone(){
		$num = $_POST["nums"];
		$where['RegDate'] =array(">",1514739600);
		$list=$this->m('user')->where($where)->limit(10)->field("Phone")->order("rand()")->select();
		echo(json_encode($list));
	}
	//摇一摇
	public function yyy(){

		//$sessonss = session("UserInfo");
		//$phone = $sessonss["phone"];
		$wxname= $_POST['wxname'];
		$OpenId= $_POST['OpenId'];
	
		if(!$OpenId) {
			$this->s("ifcj",1);
			$this->s("msg","请通过公众号正确进入");
			$this->v();
		} else {
			//$checksss["id"] = 1;//指定注册抽奖活动
			$checksss["pstatus"] = 1;//指定注册抽奖活动
			$isopen=$this->m('prize')->where($checksss)->find();
			if(!$isopen) {
				$this->s("ifcj",1);
				$this->s("msg","活动还未开始");
				$this->v();
			} else {
				$wheres["OpenId"] = $OpenId;
				$wheres["Activityid"] = $isopen['id'];
				$wheres["Ifyyy"] = 1;
				$is=$this->m('wrprize_log')->where($wheres)->find();
				if($is) {
					$this->s("msg","您已抽过奖了");
					$this->s("log",$is);
					$this->s("ifcj",1);
					$this->v();
				}else{
					//根据剩余总数来分配奖品等级
					$where["status"] = 1;
					$where["activityid"] = $isopen['id'];//指定注册抽奖活动
					$allnums = $this->m('prizetype')->where($where)->field("sum(residue) as nums")->find();
					if(!$allnums["nums"]) {
						$this->s("ifcj",1);
						$this->s("msg","活动已结束");
						$this->v();
					}

					//查询是否有此人进入页面未摇一摇(仅仅是进入页面 有这删除此人未摇一摇数据);
					$wheresw["OpenId"] = $OpenId;
					$wheresw["Activityid"] = $isopen['id'];
					$wheresw["Ifyyy"] = -1;
					$iswyyy=$this->m('wrprize_log')->where($wheresw)->find();
					if($iswyyy){//存在
						$del = $this->m('wrprize_log')->where("Id=".$iswyyy['Id'])->del();//则删除
						if(!$del){
								echo 2;exit;
							$this->s("ifcj",1);
							$this->s("msg","系统繁忙");	
							$this->v();
						}
					}

					$list = $this->m('prizetype')->where($where)->field("*")->select();
					$randnumber=mt_rand(1,$allnums["nums"]);
					$checknum=0;
					foreach ($list as $k=>$v) {
						$checknum=$v["residue"]+$checknum;
						if($checknum<$randnumber) {
							continue;// 当 $value为b时，跳出本次循环
						} else {
							$add['WxName'] = $wxname;
							$add['Prize'] = $v["name"];
							$add["CjTime"] =time();
							$add["Activityid"] =$isopen['id'];
							$add["OpenId"] =$OpenId;
							$add["Status"] =0;
							$add["Ifyyy"] =-1;
							$res = $this->m("wrprize_log")->add($add);//只要正常进入此页面的人都将记录(为了数据安全 防止修改前台)
							if($res){
								$prizetypeid =$v['id'];
							    $prizetyperesidue=$v["residue"]-1;
								$xjid = $res;
								$this->s("ifcj",2);
								$this->s("msg","获得".$v["name"]);
								$this->s("prizetypeid",$prizetypeid);
								$this->s("prizetyperesidue",$prizetyperesidue);
								$this->s("xjid",$xjid);
								$this->v();
							}else{
								$this->error("系统繁忙请稍后进入");
							}

							/*$condition["id"] =$v['id'];
							$save["residue"]=$v["residue"]-1;
							$this->m('prizetype')->where($condition)->save($save);*/
							
							break;
						}
					}
				}
				
			}
		}
	}


	public function ajaxyyy(){
		$xjid= $_REQUEST['xjid'];
		$prizetypeid= $_REQUEST['prizetypeid'];
		$prizetyperesidue= $_REQUEST['prizetyperesidue'];
		
		if(!$xjid || !$prizetypeid || (!$prizetyperesidue && $prizetyperesidue!=0)){
			echo 1;exit;
		}
		$checksss["pstatus"] = 1;//指定注册抽奖活动
		$isopen=$this->m('prize')->where($checksss)->find();
		$ifres = $this->m("wrprize_log")->where("Id=".$xjid." AND Ifyyy=-1")->find();
		

		if(!$ifres){
		
			echo 2;exit;
		}else{
			$data = array(
				'Ifyyy'	=>1
			);
			$ifsave = $this->m("wrprize_log")->where("Id=".$ifres['Id'])->save($data);
			if($ifsave){
				$condition["id"] =$prizetypeid;
				$save["residue"]=$prizetyperesidue;
				$res = $this->m('prizetype')->where($condition)->save($save);
				if($res){
					echo 3;exit;
				}else{
					echo 4;exit;
				}
			
			}else{
				echo 5;exit;
			}
			
		}
	
	
	}
}